import React, { useEffect, useRef, useState } from 'react';
import { Button, Checkbox, Empty, Icon, Input, Tabs } from '@whalecloud/fdx';
import { fetch } from '@fishx/rest';
import { request } from '@/utils/util';
import { stringify } from 'qs';
import { ReactComponent as CloseSvg } from '@/assets/icons/close.svg';
import styles from './SelectorModal.module.less';

const UserSelect = (props: any) => {
  const { multiple = false, value, onChange } = props;

  const axiosTimerRef = useRef(null);
  const initialDataCache = useRef([]);
  const currentSelValueCache = useRef([]);

  const [userList, setUserList] = useState([]);
  const [searchVisible, setSearchVisible] = useState(false);
  const [currentSelValue, setCurrentSelValue] = useState([]);

  const getUserListByKeywords = async (keywords: string) => {
    const newParam = { pageIndex: 0, pageLen: 10, fuzzyField: keywords };
    if (keywords === '' && initialDataCache.current.length) {
      setUserList(initialDataCache.current);
      return;
    }
    try {
      const res = await request(`/portal/api/users?${stringify(newParam)}`);
      if (res) {
        setUserList(res.list);
      }
    } catch (e) {
      console.log(e);
    }
  };

  const setUser = async (value: string) => {
    try {
      const res = await request(`/portal/api/users/userIds/${value}`);
      console.log(res);
      if (res) {
        setCurrentSelValue([...res]);
        currentSelValueCache.current = [...res];
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    getUserListByKeywords('');
  }, []);

  useEffect(() => {
    if (value) {
      setUser(value);
    }
  }, [value]);

  const onSearchDebounce = (event: any) => {
    if (axiosTimerRef.current) {
      clearTimeout(axiosTimerRef.current);
    }
    axiosTimerRef.current = setTimeout(getUserListByKeywords, 100, event.target.value);
  };

  const getJwt = () => {
    let jwtStr =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MzI2ODcxMzEsImlhdCI6MTYzMjY0MzkzMSwic3ViIjoid2FrZS1pZGUiLCJqdGkiOiJhZjYwM2Y4NS0zOWFiLTQ1ZjItODllZS01MjcyODA1ZGU3MTMiLCJpc3MiOiJsY2FwIiwibmJmIjoxNjMyNjQzOTMxLCJVU0VSX0NPREUiOiIwMDI3MDEwODQ0IiwiZW1haWwiOiJ3YW5nLnpoaXlvbmc2QGl3aGFsZWNsb3VkLmNvbSJ9.A04hjwpT7tuFyOE2-r5qqWR3ZMitNarbP8KlxDbuNnU';
    if (window.__lowCode__ && window.__lowCode__.webide) {
      const pathArr = window.location.pathname.split('/');
      jwtStr = pathArr.pop();
    }
    return `Bearer ${jwtStr}`;
  };

  const isCheckedOnChange = (event: any, selItem: any) => {
    const { target } = event;
    if (target.checked) {
      currentSelValueCache.current.push(selItem);
      currentSelValueCache.current = [...currentSelValueCache.current];
    } else {
      currentSelValueCache.current = currentSelValueCache.current.filter((item) => item.userId !== selItem.userId);
    }
    setCurrentSelValue(currentSelValueCache.current);
    onChange && onChange(currentSelValueCache.current);
  };

  const tabBarExtraContent = () => {
    return !searchVisible ? (
      <Button onClick={() => setSearchVisible(true)}>Search</Button>
    ) : (
      <React.Fragment>
        <Input.Search className={styles.userSelectorSearch} onChange={(event: any) => onSearchDebounce(event)} />
        <CloseSvg
          className={styles.userSelectorIcon}
          onClick={() => {
            getUserListByKeywords('');
            setSearchVisible(false);
          }}
        />
      </React.Fragment>
    );
  };

  return (
    <Tabs tabBarExtraContent={tabBarExtraContent()}>
      <Tabs.TabPane tab="全部" key="all">
        <div className={styles.userInfoList}>
          {Array.isArray(userList) &&
            userList.map((item: any) => (
              <Checkbox
                key={item.userCode}
                onChange={(event) => isCheckedOnChange(event, item)}
                className={styles.userSelectorCheckbox}
                checked={currentSelValue.filter((filItem: any) => filItem.userId === item.userId).length > 0}
                disabled={
                  !multiple && currentSelValue.length >= 1 && currentSelValue.filter((filItem: any) => filItem.userId === item.userId).length === 0
                }
              >
                <div className={styles.userInfoItem}>
                  <span className={styles.userInfoAvt}>{item.userName && item.userName.length > 2 ? item.userName.slice(-2) : item.userName}</span>
                  {item.userName} {item.userCode}
                </div>
              </Checkbox>
            ))}
          {!userList?.length && <Empty />}
        </div>
        <div className={styles.userInfoShow}>
          {currentSelValue.map((item) => (
            <div className={styles.userInfo} key={item.userId}>
              <span className={styles.userInfoAvt}>{item.userName && item.userName.length > 2 ? item.userName.slice(-2) : item.userName}</span>
              {`${item.userName} ${item.userCode}`}
              <span>
                <CloseSvg className={styles.selectedCloseIcon} onClick={() => isCheckedOnChange({ target: { checked: false } }, item)}></CloseSvg>
              </span>
            </div>
          ))}
        </div>
      </Tabs.TabPane>
    </Tabs>
  );
};

export default React.memo(UserSelect);
